/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hyce;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

/**
 *Class sets up a user interface for the Hiding/Compression/Encryption Tool.
 * 5 Buttons
 * Hide: Asks user for PNG image and message to hide. Then creates a new image with
 *      the message hidden within. Saves the new image in the original directory with
 *      an 'HY' on the end.
 * Compress: Asks user for PNG image and then compresses the image. Will save the image
 *          in the original directory with a 'C' on the end.
 * Encrypt: Asks user for a BMP image and then encrypts the image. Will save the image
 *          in the original directory with a 'E' on the end.
 * Hide/Encrypt/Compress: Will go through the Hide, Compress, and Encrypt processes
 *          with a single image. Will create 3 images: 1 for the hide, 1 for the hidden
 *          and compressed, and 1 for the hidden compressed and encrypted image. The final
 *          image will be saved in the original directory with an 'HYCE' on the end.
 * Reset: After one of the above buttons is pressed they will all be disabled except
 *      for the reset button. Clicking reset will reset class variables and allow for
 *      a clean Hide, Compress, or Encrypt sequence to be called.
 *
 * lblImagePath: Located on the top of the mainPanel. Gives the path of the final image.
 * lblImage: Located in the center of the mainPanel. Will display the final image.
 *          If the Encrypt sequence is called the image will not be viewable.
 *          Also if the image is larger than about 350 by 350 it may have trouble displaying...needs tested.
 *
 * @author AJP
 */
public class HYCEFrame extends JFrame implements ActionListener{
    JPanel mainPanel, northPanel, centerPanel, southPanel;
    JButton btnHide, btnCompress, btnEncrypt, btnHYCE, btnReset;
    JLabel lblImage, lblImagePath;
    JFileChooser fileChooser;

    String hyFilePath, hycFilePath, hyceFilePath;

    /**
     * Constructor for frame.
     */
    public HYCEFrame(){
        this.setTitle("HYCE");
        this.setSize(500, 400);
        this.setLocation(400, 150);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setResizable(false);

        initComponents();
        initUI();

    }

    /**
     * Initializes the interface items.
     */
    public void initComponents(){
        mainPanel = new JPanel(new BorderLayout());
        northPanel = new JPanel();
        centerPanel = new JPanel();
        southPanel = new JPanel();

        btnHide = new JButton("Hide");
        btnCompress = new JButton("Compress");
        btnEncrypt = new JButton("Encrypt");
        btnHYCE = new JButton("Hide/Compress/Encrypt");
        btnReset = new JButton("Reset");

        lblImage = new JLabel();
        lblImagePath = new JLabel("no image");
//        lblImage.setPreferredSize(new Dimension(256, 256));
//        lblImage.setIcon(new ImageIcon("C:\\Users\\Aaron\\desktop\\grayMars.png"));
        fileChooser = new JFileChooser();

        btnHide.addActionListener(this);
        btnCompress.addActionListener(this);
        btnEncrypt.addActionListener(this);
        btnHYCE.addActionListener(this);
        btnReset.addActionListener(this);
//        fileChooser.addActionListener(this);
    }

    /**
     * Adds the interface components to their designated panels.
     */
    public void initUI(){
        northPanel.add(lblImagePath);

//        centerPanel.add(fileChooser);
        centerPanel.add(lblImage);

        southPanel.add(btnHide);
        southPanel.add(btnCompress);
        southPanel.add(btnEncrypt);
        southPanel.add(btnHYCE);
        southPanel.add(btnReset);

        mainPanel.add(northPanel, BorderLayout.NORTH);
        mainPanel.add(centerPanel, BorderLayout.CENTER);
        mainPanel.add(southPanel, BorderLayout.SOUTH);

        this.add(mainPanel);
    }

    /**
     * Action Listeners
     * @param e
     */
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == btnHide){//Starts hiding sequence
            try{
                hyFilePath = Hide();

                if(hyFilePath != null){
                    lblImagePath.setText(hyFilePath);
                    lblImage.setIcon(new ImageIcon(hyFilePath));
                    setNeedsReset();
                }
                else
                    lblImagePath.setText("Error in hiding tool!");
            }catch(Exception ex){
                System.out.println("Exception caught during hiding sequence: " + ex.getMessage());
            }
        }
        else if(e.getSource() == btnCompress){//Starts compression sequence
            try{
                fileChooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
                public boolean accept(File f) {
                  return f.getName().toLowerCase().endsWith(".png")
                          || f.isDirectory();
                }

                public String getDescription() {
                  return "PNG Images";
                }});
                int r = fileChooser.showOpenDialog(this);
                if (r == JFileChooser.APPROVE_OPTION) {
                    String filepath = fileChooser.getSelectedFile().getPath();
                    Compress(filepath);
                    if(hycFilePath != null){
                        lblImagePath.setText(hycFilePath);
                        lblImage.setIcon(new ImageIcon(hycFilePath));
                        setNeedsReset();
                    }
                }
            }catch(Exception ex){
                System.out.println("Exception caught during compression sequence: " + ex.getMessage());
            }
        }
        else if(e.getSource() == btnEncrypt){//Starts encryption sequence
            try{
                fileChooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
                public boolean accept(File f) {
                  return f.getName().toLowerCase().endsWith(".bmp")
                          || f.isDirectory();
                }

                public String getDescription() {
                  return "BMP Images";
                }});
                int r = fileChooser.showOpenDialog(this);
                if (r == JFileChooser.APPROVE_OPTION) {
                    String filepath = fileChooser.getSelectedFile().getPath();
                    Encrypt(new File(filepath));
                    if(hyceFilePath != null){
                        lblImagePath.setText(hyceFilePath);
                        lblImage.setIcon(new ImageIcon(hyceFilePath));
                        setNeedsReset();
                    }
                }
            }catch(Exception ex){
                System.out.println("Exception caught during compression sequence: " + ex.getMessage());
            }
        }
        else if(e.getSource() == btnHYCE){
            try{
                hyFilePath = Hide();
                if(hyFilePath != null){
                    Compress(hyFilePath);
                    if(hycFilePath != null){
                        File f = new File(hycFilePath);
                        Encrypt(f);
                        if(hyceFilePath != null){
                            lblImagePath.setText(hyceFilePath);
                            lblImage.setIcon(new ImageIcon(hyceFilePath));
                            setNeedsReset();
                        }
                        else
                            lblImagePath.setText("Error in encryption tool!");
                    }
                    else
                        lblImagePath.setText("Error in compression tool!");
                }
                else
                    lblImagePath.setText("Error in hiding tool.");
            }catch(Exception ex){
                System.out.println("Exception caught during encryption sequence: " + ex.getMessage());
            }
        }
        else if(e.getSource() == btnReset){
            Reset();
        }
        else
            throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     *Asks the user to pick a PNG file and enter a message.  Then adds the message
     * to the image and saves the new image as "orig/dir/path/origFileNameHY.png"
     *
     * @return String hyFilePath which is sort of redundant since it is a class variable.
     */
    public String Hide(){
        HidingTool ht = new HidingTool();

        fileChooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
        public boolean accept(File f) {
          return f.getName().toLowerCase().endsWith(".png")
                  || f.isDirectory();
        }

        public String getDescription() {
          return "PNG Images";
        }});

        int r = fileChooser.showOpenDialog(this);
        if (r == JFileChooser.APPROVE_OPTION) {
            String filepath = fileChooser.getSelectedFile().getPath();
            String msg = JOptionPane.showInputDialog(null, "Enter the message to be hidden:");;
            hyFilePath = ht.hide(msg, filepath);
        }

        return hyFilePath;
    }

    /**
     * Compresses a file and saves it as a bitmap with the path "orig/dir/path/origFileNameHYC.png"
     *
     * @param filepath is the filepath of the file created by the hiding method.
     */
    public void Compress(String filepath){
        CompressionTool ct = new CompressionTool();
        hycFilePath = ct.compress(filepath, "PNG");
    }

    /**
     * Encrypts the compressed file from the compression tool. Saves the finished
     * product with the path "orig/dir/path/origFileNameHYCE.png"
     *
     * @param f is the file that was created from the compression tool.
     * @throws Exception
     */
    public void Encrypt(File f) throws Exception{
        FileEncryptor fe = new FileEncryptor();
//        String filename = f.getName().substring(0, f.getName().length()-4) + "E.bmp";
        hyceFilePath = f.getPath().substring(0, f.getPath().length()-4) + "E.bmp";
        String password = JOptionPane.showInputDialog("Enter an encryption password:");

        fe.encrypt(f, hyceFilePath, password);
    }

    /**
     * Disables all buttons and makes the user choose to reset before performing
     * another action.
     */
    public void setNeedsReset(){
        btnHide.setEnabled(false);
        btnCompress.setEnabled(false);
        btnEncrypt.setEnabled(false);
        btnHYCE.setEnabled(false);
    }

    /**
     * Resets all class variables. Also re-enables the buttons allowing for another
     * action to take place.
     */
    public void Reset(){
        hyFilePath = null;
        hycFilePath = null;
        hyceFilePath = null;

        lblImagePath.setText("no image");
        lblImage.setIcon(null);

        btnHide.setEnabled(true);
        btnCompress.setEnabled(true);
        btnEncrypt.setEnabled(true);
        btnHYCE.setEnabled(true);
    }
}